package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.dao.BoardMapper;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ArticleServiceImpl
 * @Description TODO
 * @Author H.
 * @Date 2023/5/31 16:58
 * @Version 1.0
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private BoardMapper boardMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public void create(Article article) {
        //非空校验
        if(article == null){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //处理默认值
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setVisitCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //调用dao层方法写入数据
        int row = articleMapper.insertSelective(article);
        if(row != 1){
            log.info(ResultCode.ERROR_INSERT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_INSERT));
        }

        //更新用户发帖数
        int userRow = userMapper.updateArticleCountById(article.getUserId());
        if(userRow != 1){
            log.info("发帖时更新用户发帖数失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        int boardRow = boardMapper.updateArticleCountById(article.getBoardId());
        if(boardRow != 1){
            log.info("发帖时更新版块数失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("帖子发布成功");
    }

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        if(boardId == null){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByBoardId(boardId);
    }

    @Override
    public Article selectDetailById(Long id) {
        if(id == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao层查询
        Article article = articleMapper.selectDetailById(id);
        //校验结果
        if(article == null){
            // 记录日志
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //更新访问量，创建新的兑现
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        //访问次数加一
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        //更新到数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            // 记录日志
            log.info(ResultCode.ERROR_SERVICES.toString() + "articleId = " + article.getId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return article;
    }

    @Override
    public Article selectById(Long id) {
        if(id == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void modify(Long id, String content) {
        //非空校验
        if(id == null || StringUtils.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验帖子状态
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        if (article.getState() == 1){
            log.warn(ResultCode.FAILED_STATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_STATE));
        }
        //创建一个用于更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        //调用Dao进行修改
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.info("更新帖子失败，articleId = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE));
        }
    }

    @Override
    public void deleteById(Long id) {
        //非空校验
        if(id == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id创建一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);
        //调用方法
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
         if(row != 1){
             log.info("删除帖子失败，articleId = " + id);
             throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE));
         }
         //根据文章id获取信息
        Article article = articleMapper.selectByPrimaryKey(id);
         //更新用户贴子数
        int userRow = userMapper.downArticleCountById(article.getUserId());
        if(userRow != 1){
            log.info("删除帖子失败，articleId = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE));
        }
        int boardRow = boardMapper.downArticleCountById(article.getBoardId());
        if(boardRow != 1){
            log.info("删除帖子失败，articleId = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE));
        }

        log.info("删除成功！");
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(userId == null){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByUserId(userId);
    }

    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if(id == null){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询文章信息并校验
        Article article = selectById(id);
        if(article == null || article.getState() == 1 || article.getDeleteState() == 1){
            log.info(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        //更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            // 记录日志
            log.info(ResultCode.ERROR_SERVICES.toString() + "articleId = " + article.getId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }


}
